package com.car.loan.project.tool.controller;

import com.car.loan.common.utils.IdUtils;
import com.car.loan.common.utils.file.FileUtils;
import com.car.loan.common.utils.qiniu.QiniuUtil;
import com.car.loan.framework.task.UploadImageTask;
import com.car.loan.framework.web.domain.AjaxResult;
import com.car.loan.project.cd.domain.vo.CreditAlbumVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.Objects;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author huangding
 * @description
 * @date 2019/10/24 20:46
 */
@RestController
@RequestMapping("/tool/pdf")
@Api(value = "工具接口", tags = "工具接口-PDF上传")
@Slf4j
public class PdfController {


    @Autowired
    private UploadImageTask uploadImageTask;

    @Autowired
    private QiniuUtil qiniuUtil;


    @PostMapping("/upload")
    @ApiOperation(value = "上传基本接口", response = CreditAlbumVo.class)
    public AjaxResult upload(@RequestParam("file") MultipartFile file, String prefix) {
        if (FileUtils.fileNameIsPdf(file.getOriginalFilename())) {
            String fileName =
                prefix + "/" + IdUtils.simpleUUID() + "." + Objects
                    .requireNonNull(file.getOriginalFilename()).split("\\.")[1];
            try {
                uploadImageTask.uploadImage(file.getBytes(), fileName);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return AjaxResult.error("上传失败，请重试");
            }
            return AjaxResult.success(new CreditAlbumVo().setDbUrl(fileName)
                .setUrl(qiniuUtil.getAuthUrl(fileName)));
        }
        return AjaxResult.error("文件格式错误，只支持PDF");
    }

}
